import React, {Component} from 'react';
import {Button} from 'antd';
import {config} from "../config";
import app from '../AppMethod';
import {customer, wechat, user} from "../value";


class Index extends Component {
    constructor(props) {
        super(props);
        this.state = {}
    }

    render() {
        return (
            <div style={{paddingTop: '50px'}}>
                <div>
                    <div style={{textAlign: 'center', marginTop: '100px'}}>
                        <Button style={{width: '96%', height: '45px', fontSize: '18px'}} type='primary'
                                onClick={() => this.handleDrop('/searchOrder')}>客户查询</Button>
                    </div>
                    <div style={{textAlign: 'center', marginTop: '60px'}}>
                        <Button style={{width: '96%', height: '45px', fontSize: '18px'}} type='primary'
                                onClick={() => this.handleDrop('/customerBind')}>客户绑定</Button>
                    </div>
                </div>
            </div>
        )
    };

    async componentDidMount() {
        let code = app.getQueryString('code');
        if (code == undefined || code == null || code.length <= 0) {
            // 有openid说明登录过，可以不用再授权登录，没有openid才用重新登录
            if(!app.getData("openid")){
                await this.handleGetOpenid();
            }
        } else {
            // 如果code相等，则是用过的登录成功code，是用户刷新当前页面或返回到这个页面，不用再授权登录
            if (code != app.getData("code")) {
                await this.handleGetUserInfo();
            }
        }
    };

    /**
     * 用户授权获取code
     * @returns {Promise.<void>}
     */
    async handleGetOpenid() {
        let result = await app.post(wechat.GET_AUTHORIZEURL, {url: window.location.href.split("#")[0]});
        if (result.code === 1) {
            let url = result.data.url;
            window.location = url;
        } else {
            this.props.history.push();
            app.alert(result.msg, 'error', 3);
        }
    };

    /**
     * 获取用户信息
     * @returns {Promise.<void>}
     */
    async handleGetUserInfo() {
        let code = app.getQueryString('code');
        let result = await app.post(wechat.GET_USERINF, {code: code});
        if (result.code === 1) {
            let data = result.data;
            app.setData("openid", data.openid);
            app.setData("nickname", data.nickname);
            app.setData("headimgurl", data.headimgurl);
            app.setData("code", code);
        } else {
            app.alert(result.msg, 'error', 2);
        }
    }

    /**
     * 处理跳转页面事件
     * @param path
     */
    handleDrop(path) {
        this.props.history.push(config.path + path);
    };
}

export default Index;